let supportedProperties = {};
const remRE = /\d?\.?\d+\s*rem/g;

function isSupportedProperty(prop, val = null) {
  const rules = supportedProperties[prop];
  if (!rules) return false;

  if (val) {
    // if (val.endsWith("vh") || val.endsWith("vw") || val.endsWith("em")) {
    if (/\d(em)$/.test(val)) {
      return false;
    }

    if (Array.isArray(rules)) {
      return rules.includes(val);
    }
  }

  return true;
}

function isSupportedRule(selector) {
  return !selector.includes(":hover");
}

function isPlaceholderPseudoSelector(selector) {
  return selector.includes("::placeholder");
}

module.exports = function (config, root, opts) {
  supportedProperties = config;
  root.walkRules(postrule => {
    if (postrule.parent.name === "media") {
      postrule.parent.remove();
    }

    if (!isSupportedRule(postrule.selector)) {
      postrule.remove();
    }

    if (isPlaceholderPseudoSelector(postrule.selector)) {
      const placeholderSelectors = [];
      postrule.selectors.forEach(selector => {
        if (isPlaceholderPseudoSelector(selector)) {
          placeholderSelectors.push(selector.replace(/::placeholder/g, ""));
        }
      });
      if (placeholderSelectors.length) {
        postrule.selectors = placeholderSelectors;
        postrule.walkDecls(decl => {
          if (decl.prop === "color") {
            decl.replaceWith(decl.clone({ prop: "placeholder-color" }));
          }
        });
      }
      // postrule.selector.replace('::placeholder', '')
    }

    postrule.walkDecls(decl => {
      if (decl.prop === "visibility") {
        switch (decl.value) {
          case "hidden":
            decl.replaceWith(decl.clone({ value: "collapse" }));
            return;
        }
      }

      if (decl.prop === "vertical-align") {
        switch (decl.value) {
          case "middle":
            decl.replaceWith(decl.clone({ value: "center" }));
            return;
        }
      }

      if (
        !decl.prop.startsWith("--") &&
        !isSupportedProperty(decl.prop, decl.value)
      ) {
        postrule.removeChild(decl);

        if (postrule.nodes.length === 0) {
          postrule.remove();
        }
      }
    });
  });
};
